package com.bawei.module_mine.tengxun

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.PopupMenu
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.lib_common.mvi.base.BaseActivity
import com.bawei.module_mine.R
import com.bawei.module_mine.databinding.ActivityTengxunBinding
import com.bawei.module_mine.tengxun.mvi.intent.LiveIntent
import com.bawei.module_mine.tengxun.mvi.model.entity.CreateLiveRoomEntity
import com.bawei.module_mine.tengxun.mvi.state.LiveState
import com.blankj.utilcode.util.ToastUtils
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.tencent.rtmp.TXLivePushConfig
import com.tencent.rtmp.TXLivePusher
import kotlinx.coroutines.launch
import android.widget.Button
import com.bawei.module_mine.tengxun.mvi.model.entity.SendRedPacketEntity
import com.bawei.module_mine.tengxun.mvi.viewmodel.LiveViewModel
import com.bawei.module_mine.tengxun.websocket.SafeWebSocketListener
import com.tencent.mmkv.MMKV
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import org.json.JSONObject
import java.lang.ref.WeakReference
import kotlin.math.roundToInt
import kotlin.properties.Delegates


@Route(path = "/module_mine/TengxunActivity")
class TengxunActivity : BaseActivity() {
    private lateinit var liveViewModel: LiveViewModel
    private val binding: ActivityTengxunBinding by lazy {
        ActivityTengxunBinding.inflate(layoutInflater)
    }
    var mLivePushConfig: TXLivePushConfig = TXLivePushConfig()
    private lateinit var mLivePusher: TXLivePusher
    private var bottomSheetDialog: BottomSheetDialog? = null
    private var countOptions: List<TextView>? = null
    private var countOptions2: List<TextView>? = null
    private var selectedCountIndex = 0
    private var selectedDiamondIndex = 0
    private val countValues = listOf(20, 50, 100, -1) // -1代表自定义
    private val diamondValues = listOf(1, 3, 10, -1) // -1代表自定义
    private lateinit var btnSend: Button

//    private lateinit var wsManager: LiveWebSocketManager
var roomId="111"
    private var userId by Delegates.notNull<Int>()
    private lateinit var sendRedPacketEntity: SendRedPacketEntity
    private var webSocket: WebSocket? = null

    override fun getLayoutRootView(): View {
        return binding.root
    }

    override fun initView() {
        super.initView()
        liveViewModel = ViewModelProvider(this)[LiveViewModel::class.java]

        sendRedPacketEntity = SendRedPacketEntity(1, 10, "111", 10000)
        //初始化红包弹窗
        initRedPacketDialog()



        userId = MMKV.defaultMMKV().decodeInt("userId")

        mLivePusher = TXLivePusher(this)
        // 一般情况下不需要修改 config 的默认配置
        mLivePusher.setConfig(mLivePushConfig);
        //启动本地摄像头预览
        mLivePusher.startCameraPreview(binding.pusherTxCloudView);

        //每次开直播创建一个新的直播间
        val createLiveRoom = CreateLiveRoomEntity("新主播", "111", "111")

        //发送意图
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                liveViewModel.intents.send(LiveIntent.createLiveRoom(createLiveRoom))
                liveViewModel.handleIntent()
            }
        }

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                liveViewModel.liveFlow_.collect {
                    when (it) {
                        is LiveState.Init -> {
                            showMsg("初始化")
                        }

                        is LiveState.Empty -> {
                            showMsg("空")
                        }

                        is LiveState.Failed -> {
                            showMsg("失败_推流ht")
                        }

                        is LiveState.VideoSuccess -> {
                            val rtmpURL = it.liveRoomEntity!!.push_url //此处填写您的 rtmp 推流地址
                            val ret = mLivePusher.startPusher(rtmpURL.trim { it <= ' ' })
                            if (ret == -5) {
                                Log.i("tuiliu", "startRTMPPush: license 校验失败")
                            }
                            roomId = it.liveRoomEntity.room_id
                            Log.d("redpacket_roomid", roomId)
                        }

                        else -> {}
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                liveViewModel.sendRedPackliveFlow_.collect {
                    when (it) {
                        is LiveState.Init -> {
                            showMsg("初始化")
                        }

                        is LiveState.Empty -> {
                            showMsg("空")
                        }

                        is LiveState.Failed -> {
                            showMsg("失败_发红包ht")
                        }

                        is LiveState.SendRedPacketSuccess -> {
                            ToastUtils.showShort("发送红包成功")
                        }

                        else -> {}
                    }
                }
            }
        }
    }

    private fun showExitConfirmDialog() {
        AlertDialog.Builder(this)
            .setTitle("退出直播")
            .setMessage("是否关闭直播间？")
            .setPositiveButton("关闭直播间") { _, _ ->
                closeLiveRoom()
            }
            .setNegativeButton("留在直播间") { _, _ ->
                // 什么都不做，用户留在直播间
            }
            .setCancelable(false)
            .show()
    }

    private fun closeLiveRoom() {
        // 停止推流
        mLivePusher?.let { pusher ->
            pusher.stopPusher()
            mLivePusher.stopCameraPreview(true); //如果已经启动了摄像头预览，请在结束推流时将其关闭。
        }

        // 如果有后端接口，调用关闭直播间
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                liveViewModel.deleteliveFlow_.collect {
                    when (it) {
                        is LiveState.Init -> {
                            showMsg("初始化")
                        }

                        is LiveState.Empty -> {
                            showMsg("空")
                        }

                        is LiveState.Failed -> {
                            showMsg("失败_关闭直播件ht")
                        }

                        is LiveState.VideoSuccess -> {
                            ToastUtils.showShort("删除直播间成功")
                        }

                        else -> {}
                    }
                }
            }
        }

        // 显示关闭成功提示
        showMsg("直播间关闭成功")

//         延迟退出页面
        Handler(Looper.getMainLooper()).postDelayed({
            finish()
        }, 1500)
    }

    override fun initData() {
        super.initData()


        binding.hudongImg!!.setOnClickListener {
            binding.hudongList!!.visibility = View.VISIBLE
        }
        binding.zong!!.setOnClickListener {
            binding.hudongList!!.visibility = View.GONE
        }

        binding.redPacket!!.setOnClickListener {
            initRedPacketDialog()
            if (bottomSheetDialog?.isShowing == true) {
                bottomSheetDialog?.dismiss()
            } else {
                bottomSheetDialog?.show()
            }
        }

        binding.moreImg!!.setOnClickListener {
            // 创建 PopupMenu
            val popupMenu = PopupMenu(this, binding.moreImg!!)
            // 添加菜单项
            popupMenu.menu.add(0, 1, 0, "发红包")
            popupMenu.menu.add(0, 2, 1, "更多")
            // 菜单点击事件
            popupMenu.setOnMenuItemClickListener { item: MenuItem ->
                when (item.itemId) {
                    1 -> {
                        ToastUtils.showShort("点击了发红包")
                        // TODO: 跳转发红包页面或弹窗
                        true
                    }

                    2 -> {
                        ToastUtils.showShort("点击了更多")
                        // TODO: 处理更多逻辑
                        true
                    }

                    else -> false
                }
            }
            popupMenu.show()
        }
    }

    //初始化红包弹窗布局
    private fun initRedPacketDialog() {
        if (bottomSheetDialog == null) {
            bottomSheetDialog = BottomSheetDialog(this)
            val dialogView =
                LayoutInflater.from(this).inflate(R.layout.activity_fans_red_packet, null)

            countOptions = listOf(
                dialogView.findViewById(R.id.tv_count_20),
                dialogView.findViewById(R.id.tv_count_50),
                dialogView.findViewById(R.id.tv_count_100),
                dialogView.findViewById(R.id.tv_count_custom)
            )

            countOptions2 = listOf(
                dialogView.findViewById(R.id.tv_count_1),
                dialogView.findViewById(R.id.tv_count_3),
                dialogView.findViewById(R.id.tv_count_10),
                dialogView.findViewById(R.id.tv_count_zuan)
            )
            btnSend = dialogView.findViewById(R.id.btn_send)

            countOptions?.forEachIndexed { index, textView ->
                textView.setOnClickListener {
                    selectedCountIndex = index
                    updateCountSelection(index, countOptions!!)
                    updateSendButtonText()
                }
            }
            countOptions2?.forEachIndexed { index, textView ->
                textView.setOnClickListener {
                    selectedDiamondIndex = index
                    updateCountSelection(index, countOptions2!!)
                    updateSendButtonText()
                }
            }

            // 初始选中
            updateCountSelection(selectedCountIndex, countOptions!!)
            updateCountSelection(selectedDiamondIndex, countOptions2!!)
            updateSendButtonText()

            btnSend.setOnClickListener {
                val count =
                    if (countValues[selectedCountIndex] == -1) 1 else countValues[selectedCountIndex] // 这里可加自定义逻辑
                val diamond =
                    if (diamondValues[selectedDiamondIndex] == -1) 1 else diamondValues[selectedDiamondIndex]
                val total = count * diamond
                bottomSheetDialog?.dismiss()
                //Toast.makeText(this, "发送红包（$total）", Toast.LENGTH_SHORT).show()

//                wsManager.sendRedPacket(count, diamond,roomId,userId)
//                bottomSheetDialog?.dismiss()
//                Toast.makeText(this, "发送红包（${count * diamond}）", Toast.LENGTH_SHORT).show()
                bottomSheetDialog?.dismiss()
                //初始化红包websocket
                initWebSocket()


                sendRedPacketEntity = SendRedPacketEntity(count, diamond, "111", 10000)
                lifecycleScope.launch {
                    repeatOnLifecycle(Lifecycle.State.STARTED) {
                        liveViewModel.intents.send(LiveIntent.sendRedPacket(sendRedPacketEntity))
                        liveViewModel.handleIntent()
                    }
                }


            }
            bottomSheetDialog?.setContentView(dialogView)
            bottomSheetDialog?.setCanceledOnTouchOutside(true)
            bottomSheetDialog?.setOnShowListener { dialog ->
                val d = dialog as BottomSheetDialog
                val bottomSheet =
                    d.findViewById<FrameLayout>(com.google.android.material.R.id.design_bottom_sheet)
                bottomSheet?.layoutParams?.height = ViewGroup.LayoutParams.MATCH_PARENT
                bottomSheet?.requestLayout()
            }
        }
    }

    //红包选择颜色变化
    private fun updateCountSelection(selectedIndex: Int, countOptions: List<TextView>) {
        countOptions.forEachIndexed { index, textView ->
            if (index == selectedIndex) {
                textView.setBackgroundResource(R.drawable.bg_red_border_select)
                textView.setTextColor(Color.parseColor("#FB4062"))
            } else {
                textView.setBackgroundResource(R.drawable.bg_red_boder_gray)
                textView.setTextColor(Color.parseColor("#333333"))
            }
        }
    }

    private fun updateSendButtonText() {
        val count =
            if (countValues[selectedCountIndex] == -1) 1 else countValues[selectedCountIndex] // 这里可加自定义逻辑
        val diamond =
            if (diamondValues[selectedDiamondIndex] == -1) 1 else diamondValues[selectedDiamondIndex]
        val total = count * diamond
        btnSend.text = "塞钱进红包（$total）钻石"
    }


    override fun onDestroy() {
        webSocket?.close(1000, "bye")
        webSocket?.cancel()  // 比close()更强制性地中断连接
        webSocket = null
        super.onDestroy()
    }

    //按返回键弹出对话框选择是否退出直播间
    @SuppressLint("MissingSuperCall")
    override fun onBackPressed() {
        //发送删除直播间意图
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                liveViewModel.intents.send(LiveIntent.deleteLiveRoom("111"))
                liveViewModel.handleIntent()
            }
        }
        showExitConfirmDialog()
    }

    fun showRedPacketDialog(count: Int, diamond: Int) {
        // 这里弹出你自定义的红包弹窗
        AlertDialog.Builder(this)
            .setTitle("红包成功发送")
            .setMessage("已发送发了${count}个红包，每个${diamond} 钻石")
            .setPositiveButton("知道了", null)
            .show()
    }
    private fun initWebSocket() {
        val client = OkHttpClient()
        val request: Request = Request.Builder()
            .url("ws://10.161.9.80:7015/liveRoom/websocket/${111}/${5}")
            .build()
        webSocket = client.newWebSocket(request, SafeWebSocketListener(this))
//        val client = OkHttpClient()
//        val request: Request = Request.Builder()
//            .url("ws://10.161.9.80:7015/liveRoom/websocket/${111}/${5}")
//            .build()
//        webSocket = client.newWebSocket(request, object : WebSocketListener() {
//            override fun onMessage(webSocket: WebSocket, text: String) {
//                val json= JSONObject(text)
//                val type=json.optInt("type")
//                if (type==5){
//                    val data=json.optJSONObject("data")
//                    val username=data?.optString("username")
//                    if (!username.isNullOrEmpty()){
//                        runOnUiThread {
//                            ToastUtils.showShort("$username 加入直播间")
//                        }
//                    }
//
//                }
//                if (type==1){
//                    val data=json.optJSONObject("data")
//                    val roomId=data?.optString("room_id")
//                    val count=data?.optInt("count")
//                    val money=data?.optDouble("money")
//                    val time=data?.optInt("time")
//                    val createTime=data?.optString("createTime")
//
//                    runOnUiThread {
//                        showRedPacketDialog(count!!, money!!.roundToInt())
//                    }
//                }
//
//            }
//
//            override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
//
//            }
//
//            override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
//                // 处理断线重连等
//                //Log.e("WebSocket", "连接失败: ${t.message}")
//            }
//
//            override fun onOpen(webSocket: WebSocket, response: Response) {
//                Log.d("WebSocket","redPacket---open")
//                Log.d("WebSocket", "连接已建立，房间号:$roomId")
//                Log.d("WebSocket", webSocket.request().url.toString())
//            }
//
//            override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
//                Log.d("WebSocket","redPacket---close")
//            }
//
//        })
    }




}

